package com.ls.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.blog.common.exception.BizException;
import com.ls.blog.dto.CategoryDTO;
import com.ls.blog.entity.Article;
import com.ls.blog.entity.Category;
import com.ls.blog.mapper.ArticleMapper;
import com.ls.blog.mapper.CategoryMapper;
import com.ls.blog.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.blog.utils.ObjectUtils;
import com.ls.blog.vo.CategoryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lishun
 * @since 2022-01-16
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public List<CategoryDTO> listCategoryDTO() {
        return categoryMapper.listCategoryDTO();
    }


    @Override
    public CategoryDTO getCategoryById(Long id) {
        Category category = categoryMapper.selectById(id);
        return ObjectUtils.copyObject(category,CategoryDTO.class);
    }

    @Override
    public void updateCategory(CategoryVO categoryVO) {
        // 校验是否分类名重复
        isExitByCategoryName(categoryVO);
        this.updateById(ObjectUtils.copyObject(categoryVO,Category.class));
    }

    @Override
    public void saveCategory(CategoryVO categoryVO) {
        // 判断分类名是否已经存在
        isExitByCategoryName(categoryVO);
        this.save(ObjectUtils.copyObject(categoryVO,Category.class));
    }

    protected void isExitByCategoryName(CategoryVO categoryVO){
        // 判断分类名是否已经存在
        Long count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getName, categoryVO.getName()));
        if (count>0){
            throw new BizException("分类名已经存在");
        }
    }

    @Override
    public void deleteCategory(Long id) {
        // 查询分类下是否有文章
        Long count = articleMapper.selectCount(new LambdaQueryWrapper<Article>().eq(Article::getCategoryId, id));
        if (count>0){
            throw new BizException(String.format("分类下存在%s篇文章",count));
        }
        this.removeById(id);
    }
}
